package com.supermap.dataHandling.controller;

import com.supermap.dataHandling.restFul.ResultEntity;
import com.supermap.dataHandling.restFul.ResultManger;
import com.supermap.dataHandling.service.WordService;
import com.supermap.dataHandling.utils.StringUtil;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/word")
public class WordController {

    @Autowired
    private WordService wordService;

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResultEntity download(@RequestParam String dir, HttpServletResponse response, HttpServletRequest request){
        String s = dir.replaceAll("/", "\\\\");
        String downloadDir = s + "\\输出文件夹\\报告模板表格输出";
        List<String> list = StringUtil.parseYearAndMonth(downloadDir);
        File file = null;
        String fileName = null;
        try {

            file = wordService.createWord(downloadDir, list.get(0), list.get(1), list.get(2));
            wordService.downloadWord();
            InputStream inputStream = new FileInputStream(file);
            OutputStream outputStream = response.getOutputStream();
            String userAgent = request.getHeader("User-Agent");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")){
                fileName = URLEncoder.encode(file.getName(),"UTF-8");
            }else {
                fileName = new String(file.getName().getBytes("UTF-8"),"ISO-8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }

        return ResultManger.success();
    }
}
